<template>
	<view class="search" :style="{paddingTop: paddingHeight + 'px'}">
		<nav-bar></nav-bar>
		<view class="continer">
			<view class="search_s" v-if="status == 'search'">
                <view class="device-box">
					<view class="device-icon">
						<image
							src="http://oss.antaimedical.com/images/pro/2025/02/67aaafede4b0d615350f3132pYjgcEHuZAd81bad78b02f6cb0bbe5e1bc0c3bb90581.png"
							class="img"
						/>
					</view>
					<view class="device-bg">
						<view class="radar_container">
							<view class="radar_wave"></view>
							<view class="radar_wave"></view>
							<view class="radar_wave"></view>
						</view>
					</view>
				</view>
				<view class="hint">
					1.请确保您的仪器已开启，且距离此手机{{ `<1m` }}
					<br />
					2.请确保您的手机蓝牙已开启
					<br />
					3.此界面最多停留30s
				</view>
			</view>
			<view class="search_n" v-else-if="status == 'none'">
				<image
					src="http://oss.antaimedical.com/images/pro/2025/02/67aae64be4b0be9d4442343e8jrbCUlXudV64c14e2171ac079bf8cad8dd07fd18547.png"
					class="search_w_e"
				/>
				<view class="tips"> 未搜索到仪器 </view>
				<view class="again" @click="$u.throttle(againSearch, 1500)">
					重新搜索
				</view>
				<view class="hint">
					1.请确保您的仪器已开启，且距离此手机{{ `<1m` }}
					<br />
					2.请确保您的手机蓝牙已开启
				</view>
			</view>
			<view class="search_f" v-else-if="status == 'fail'">
				<image
					src="http://oss.antaimedical.com/images/pro/2025/02/67aae64be4b0be9d4442343e8jrbCUlXudV64c14e2171ac079bf8cad8dd07fd18547.png"
					class="search_w_e"
				/>
				<view class="tips"> 绑定失败 </view>
				<view class="again" @click="$u.throttle(againSearch, 1500)">
					重新绑定
				</view>
				<view class="hint">
					1.请确保您的仪器已开启，且距离此手机{{ `<1m` }}
					<br />
					2.请确保您的手机蓝牙已开启
				</view>
			</view>
			<view class="search-d" v-else-if="status == 'default'">
				<view class="title">
					仪器已绑定
				</view>
				<view class="device_c">
					<image :src="img_2" class="device_i" />
					<view class="device_name">
						蓝牙名: {{ ble.defaultInfo.name ? ble.defaultInfo.name : deviceInfo.bluetoothName }}
					</view>
					<view class="info">
						<view class="battery" v-if="ble.state == 0">
							<text style="padding-right: 8rpx;"
								v-if="ble.defaultInfo.battery">{{ ble.defaultInfo.battery }}%</text>
							<u-loading-icon v-else size="18" :show="true"></u-loading-icon>
							<u-image width="44rpx" height="26rpx" :showMenuByLongpress="false" :showError="false"
								:src="myGetBatteryIcon(ble.defaultInfo.battery)" :showLoading="false"
								:lazy-load="true"></u-image>
						</view>
						<view class="line"></view>
						<view class="mac">
							地址: {{ ble.defaultInfo.mac ? ble.defaultInfo.mac : deviceInfo.deviceMac }}
						</view>
					</view>
					<view class="version">
						版本号: {{ ble.defaultInfo.version ? ble.defaultInfo.version : '' }}
					</view>
				</view>
				<view class="next_step" @click="$u.throttle(next, 1500)">
					下一步
				</view>
				<view class="unbind" @click="$u.throttle(unbind, 1500)">
					解绑
				</view>
			</view>
		</view>
		<u-popup :show="showDeviceList" :closeOnClickOverlay="false" mode="bottom" :round="10"
			@close="showDeviceList = false">
			<view class="pop">
				<picker-view :immediate-change="true" class="picker-view" indicator-class="picker-indicator"
					mask-class="picker-mask" :value="value" @change="bindChange">
					<picker-view-column class="picker-column">
						<view v-for="(item,index) in devices" :key="index" class="picker-item">{{item.name}}
						</view>
					</picker-view-column>
				</picker-view>
				<view class="handleBle">
					<view class="cancel" @click="$u.throttle(back,2000)">
						取消
					</view>
					<view class="confirm" @click="$u.throttle(masktrue,2000)">
						确定
					</view>
				</view>
			</view>

		</u-popup>
	</view>
</template>

<script>
	import {
		addDevice,
		unbindDevice
	} from '@/api/index.js'
	import {
		ab2hex,
		getBatteryIcon
	} from '@/utils/utils.js'
	import {
		mapState
	} from 'vuex'
	const BLE = require('@/utils/ble.js');
	export default {
		data() {
			return {
				paddingHeight: uni.getStorageSync('navbarHeight'),
				userId: uni.getStorageSync("userId"),
				img_2: 'http://oss.antaimedical.com/images/static/2024/08/66b47bc1e4b000d2c606b524bblrMJK2gq935a3581f5f3a72a294dcfd449f2b1e19c.png',
				value: [0], // 仪器列表默认项
				showDeviceList: false,
				devices: [],
				timer: null,
				currentPickerIndex: 0, // 当前点击选择的仪器下标  默认第一项
				status: 'search',
				type: '', // 跳转类型
				deviceInfo: undefined,
				timeout: undefined
			}
		},
		onLoad(OPTIONS) {
			if (OPTIONS.type) this.type = OPTIONS.type
			this.registerAdapter()
		},
		onUnload() {
			clearTimeout(this.timeout)
			clearTimeout(this.timer)
			wx.offBluetoothAdapterStateChange()
			wx.stopBluetoothDevicesDiscovery()
			uni.$emit('refreshDevice')
		},
		watch: {
			showDeviceList(nVal, oVal) {
				if (nVal) {
					clearTimeout(this.timer)
				}
			}
		},
		computed: {
			...mapState({
				ble: state => state.ble, // 实时蓝牙全局状态
				userInfo: state => state.userInfo
			})
		},
		methods: {
			next() {
				uni.navigateBack()
			},
			// 确定选择蓝牙连接
			masktrue() {
				wx.stopBluetoothDevicesDiscovery()
				this.showDeviceList = false
				this.bind()
			},
			// 开始绑定仪器
			async bind() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					bluetoothName: this.devices[this.currentPickerIndex].localName,
					deviceMac: '',
					modelNumber: '',
					userId: this.userId,
					urlencoded: true
				}
				if (uni.$u.os() == 'android') {
					params.deviceMac = this.devices[this.currentPickerIndex].deviceId
				} else if (uni.$u.os() == 'ios') {
					let data = this.devices[this.currentPickerIndex].mac
					for (let i = 0; i < data.length; i++) {
						params.deviceMac += data[i];
						if (i % 2 === 1 && i != data.length - 1) params.deviceMac += ':';
					}
					params.deviceMac = params.deviceMac.toLocaleUpperCase()
				}
				try {
					const res = await addDevice(params)
					if (res.code == 200) {
						this.showDeviceList = false
						uni.showToast({
							title: '添加成功'
						})
						uni.$emit('refreshDevice')
						this.deviceInfo = res.data
						this.$store.commit('setDefaultInfo', {
							type: 1,
							data: {
								mac: params.deviceMac,
								name: params.bluetoothName
							}
						})
						this.status = 'default'
						this.createBLEConnectionFn(this.devices[this.currentPickerIndex])
					} else if (res.code == 'D0002') {
						uni.showModal({
							title: '提示',
							content: res.msg,
							confirmColor: '#545DDE',
							showCancel: false,
							success: (t_res) => {
								if (t_res.confirm) {
									this.status = 'fail'
								}
							}
						});
					}
				} catch (e) {
					//TODO handle the exception
					uni.showToast({
						title: '添加失败',
						icon: 'none'
					})
					this.status = 'fail'
				}
				uni.hideLoading()
			},

			// 注册蓝牙功能
			registerAdapter() {
				let that = this
				if (this.ble.isOpenBleAdapter) {
					wx.getBluetoothAdapterState({
						success: res => {
							if (!res.available) {
								uni.showModal({
									title: '提示',
									content: '检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
									showCancel: false,
									confirmColor: '#545DDE',
									success(b_res) {
										if (b_res.confirm) {
											setTimeout(() => {
												if (!that.devices.length) {
													wx.offBluetoothAdapterStateChange()
													that.status = 'none'
												}
											}, 10000)
											wx.onBluetoothAdapterStateChange(function(res) {
												if (res.available) {
													wx.offBluetoothAdapterStateChange()
													that.myStartBluetoothDevicesDiscovery()
												}
											})
										}
									}
								})
							} else {
								that.myStartBluetoothDevicesDiscovery()
							}
						},
						fail: err => {
							uni.showModal({
								title: '提示',
								content: '请检查蓝牙功能是否正常',
								showCancel: false
							})
						}
					})
				} else {
					wx.closeBluetoothAdapter()
					wx.openBluetoothAdapter({
						success(BleObj) {
							that.$store.commit('changeIsOpenBleAdapter', true)
							that.myStartBluetoothDevicesDiscovery()
						},
						fail(err) {
							console.log('openBluetoothAdapter', err)
							if (err.errCode == 10001) {
								that.$store.commit('changeIsOpenBleAdapter', true)
								uni.showModal({
									title: '提示',
									content: '检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
									showCancel: false,
									confirmColor: '#545DDE',
									success(b_res) {
										if (b_res.confirm) {
											that.timeout = setTimeout(() => {
												if (!that.devices.length) {
													wx.offBluetoothAdapterStateChange()
													that.status = 'none'
												}
											}, 10000)
											wx.onBluetoothAdapterStateChange(function(res) {
												if (res.available) {
													clearTimeout(that.timeout)
													wx.offBluetoothAdapterStateChange()
													that.myStartBluetoothDevicesDiscovery()
												}
											})
										}
									}
								})
							}
							if (err.errMsg == 'openBluetoothAdapter:fail auth deny') {
								uni.showModal({
									title: '提示',
									content: '请先授权蓝牙权限',
									confirmColor: '#545DDE',
									success(modal_res) {
										if (modal_res.confirm) {
											wx.openSetting({
												success: (authData) => {
													if (authData.authSetting[
															'scope.bluetooth']) {
														that.registerAdapter()
													} else { // 未授权
														uni.showModal({
															title: '提示',
															content: '授权失败,您将无法使用蓝牙相关服务',
															confirmColor: '#545DDE',
															showCancel: false,
															success(modal) {
																if (modal
																	.confirm) {
																	wx.closeBluetoothAdapter()
																	that.$store.commit(
																		'changeIsOpenBleAdapter',
																		false)
																	uni.reLaunch({
																		url: '/pagesB/login/index'
																	})
																}
															}
														})

													}
												}
											})
										} else {
											uni.showModal({
												title: '提示',
												content: '授权失败,您将无法使用蓝牙相关服务',
												confirmColor: '#545DDE',
												showCancel: false,
												success(modal) {
													if (modal.confirm) {
														wx.closeBluetoothAdapter()
														that.$store.commit(
															'changeIsOpenBleAdapter',
															false)
														uni.reLaunch({
															url: '/pagesB/login/index'
														})
													}
												}
											})
										}
									}
								})
							}
						}
					})
				}
			},
			// 开始搜寻周边仪器
			myStartBluetoothDevicesDiscovery() {
				console.log('开始搜索');
				if (uni.$u.os() == 'android') {
					uni.getLocation({
						type: 'wgs84',
						fail: err => {
							console.log('getLocationfail', err);
							uni.showModal({
								title: '提示',
								content: '因系统要求,小程序绑定蓝牙仪器需获取位置信息权限,请检查手机微信是否授权位置权限或检查手机是否开启GPS功能',
								showCancel: false,
								success(modal) {
									if (modal.confirm) {
										uni.openAppAuthorizeSetting({
											fail: err => {
												uni.navigateBack()
											}
										})
									}
								}
							})
							return
						}
					});
				}
				if (this.ble.state == 0) { // 此时已经处于连接状态下
					wx.closeBLEConnection({ // 断开
						deviceId: this.ble.devID,
						success: () => {
							this.myStartBluetoothDevicesDiscovery()
							return // 断掉上一次连接结束此次方法
						}
					})
				}
				wx.startBluetoothDevicesDiscovery({
					powerLevel: 'medium',
					allowDuplicatesKey: true,
					success: (res) => {
						this.$store.commit('changeBleState', -2)
						this.MYonBluetoothDeviceFound()
						// 十秒后未搜索到仪器显示提示
						this.timer = setTimeout(() => {
							if (!this.devices.length) {
								// 关闭蓝牙模块使用
								this.$store.commit('changeBleState', -5)
								wx.stopBluetoothDevicesDiscovery()
								wx.offBluetoothDeviceFound()
								this.status = 'none'
							}
						}, 15000)
					},
					fail: (err) => {
						this.$store.commit('changeBleState', -4)
						console.log('startBluetoothDevicesDiscovery', err);
					}
				});
			},
			// 搜索仪器回调
			MYonBluetoothDeviceFound() {
				let that = this
				// 监听寻找到新仪器的事件
				wx.onBluetoothDeviceFound((res) => {
					console.log('search', JSON.stringify(res.devices))
					res.devices.forEach(item => {
						if (!item.localName) return // 过滤掉名称为空的仪器
						// 判断是否为本公司仪器标识
						if (item.localName.startsWith('ANT') && item.advertisData) {
							// 检测搜索的仪器是否存在在仪器列表里
							const idx = that.inArray(that.devices, 'localName', item
								.localName);
							if (idx === -1) {
								let device = {
									...item,
									mac: ab2hex(item.advertisData)
								}
								// 如果不存在则添加
								that.devices.push(device)
								that.showDeviceList = true
							}
						}
					})
				})
			},
			// 建立连接低功耗蓝牙仪器
			createBLEConnectionFn(devInfo) {
				let _self = this
				// 连接低功耗蓝牙仪器
				wx.createBLEConnection({
					deviceId: devInfo.deviceId,
					timeout: 20000,
					success: (res) => {
						console.log('createBLEConnectionFn', res)
						if (getApp().globalData.isAndroid) {
							wx.setBLEMTU({
								deviceId: devInfo.deviceId,
								mtu: 300,
								success: (res) => {
									console.log('setBLEMTU', res)
								},
								fail: (err) => {
									console.log('setBLEMTUfail', err)
								}
							})
						}
						_self.$store.commit('changeBleState', 0)
						_self.$store.commit('setDevId', devInfo.deviceId)
						uni.setStorageSync('serial', 0)
						BLE.common.getBLEDeviceServices(devInfo.deviceId);
						BLE.common.onBLEConnectionStateChange(devInfo.deviceId);
					},
					fail: (err) => {
						console.log('connect fail', err);
						_self.status = 'fail'
						if (err.errMsg.indexOf('time out') == -1) {
							_self.$store.commit('changeBleState', -4)
						} else {
							_self.$store.commit('changeBleState', -5)
						}
					}
				})
			},
			// 解绑仪器
			async unbind() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					id: this.deviceInfo.id,
					userId: this.userId,
					urlencoded: true
				}
				try {
					const res = await unbindDevice(params)
					uni.hideLoading()
					if (res.code == 200) {
						uni.showToast({
							title: '解绑成功'
						})
						uni.$emit('refreshDevice')
						if (this.ble.devID) {
							wx.closeBLEConnection({
								deviceId: this.ble.devID,
								success: () => {
									console.log('断开成功')
									// 继续搜索新仪器
									this.devices = []
									this.status = 'search'
									setTimeout(() => {
										this.registerAdapter()
									}, 1500)
								}
							})
						} else {
							// 继续搜索新仪器
							this.devices = []
							this.status = 'search'
							setTimeout(() => {
								this.registerAdapter()
							}, 1500)
						}
					}
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
				}
			},
			againSearch() {
				this.currentPickerIndex = 0
				this.devices = []
				this.status = 'search'
				this.registerAdapter()
			},
			bindChange(e) {
				this.currentPickerIndex = e.detail.value[0]
			},
			back() {
				console.log('返回');
				wx.stopBluetoothDevicesDiscovery()
				this.showDeviceList = false
				this.status = 'none'
				this.$store.commit('changeBleState', -4)
			},
			myGetBatteryIcon(data) {
				return getBatteryIcon(data)
			},
			inArray(arr, key, val) {
				for (let i = 0; i < arr.length; i++) {
					if (arr[i][key] === val) {
						return i;
					}
				}
				return -1;
			}
		}
	}
</script>
<style lang="scss">
	page {
		background-color: #fff;
		min-height: 100%;
	}
</style>

<style lang="scss" scoped>
.continer {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
    padding: 0 26rpx;
	.search_f,
	.search_n,
	.search_s {
		display: inherit;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;

		.search_img {
			width: 486rpx;
			height: 486rpx;
			margin: 70rpx auto 40rpx;
		}

		.tips {
			font-weight: 500;
			font-size: 28rpx;
			color: #1F2434;
		}

		.search_w_e {
			width: 85rpx;
			height: 85rpx;
			margin: 200rpx 0 38rpx;
		}

		.again {
			width: 424rpx;
            height: 86rpx;
			margin-top: 84rpx;
			background: #1F2434;
			border-radius: 64rpx;
			line-height: 86rpx;
			text-align: center;
			font-size: 28rpx;
			color: #ffffff;
		}
		.hint {
            width: 100%;
			margin-top: 154rpx;
			padding: 38rpx;
			background: #F3F4F7;
			border-radius: 16rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 26rpx;
			color: rgba(31,36,52,0.7);
			line-height: 48rpx;
			text-align: left;
		}
	}

	.search-d {
		margin-top: 45rpx;
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.title {
			font-weight: 500;
			font-size: 48rpx;
			color: #333333;
			line-height: 66rpx;
		}

		.device_c {
			margin: 80rpx 0 188rpx;
			width: 90%;
			padding: 112rpx 0 80rpx;
			background: #fafafa;
			border-radius: 16rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.device_i {
				width: 120rpx;
				height: 320rpx;
			}

			.device_name {
				margin: 64rpx 0 32rpx;
				font-weight: 500;
				font-size: 32rpx;
				color: #333333;
				line-height: 44rpx;
			}

			.info {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 16rpx;
				font-size: 24rpx;
				color: #666666;

				.line {
					width: 1rpx;
					height: 24rpx;
					background-color: rgba(0, 0, 0, 0.1);
					margin: 0 16rpx;
				}

				.battery {
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.version {
				font-size: 24rpx;
				color: #666666;
			}
		}

		.unbind,
		.next_step {
			width: 80%;
			height: 88rpx;
			line-height: 80rpx;
			background-color: #ffffff;
			border: 2rpx solid #1F2434;
			text-align: center;
			font-size: 36rpx;
			color: #1F2434;
			border-radius: 16rpx;
		}

		.unbind {
			margin-top: 32rpx;
			background-color: #1F2434;
			color: #ffffff;
			border: 0;
			line-height: 88rpx;
		}
	}
	.search_s {
		.device-box {
			width: 231rpx;
			height: 231rpx;
			position: relative;
			display: flex;
			justify-content: center;
			align-items: center;
            margin-top: 150rpx;
            border-radius: 50%;
            overflow: hidden;
			.device-icon {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
                z-index: 2;
				width: 104rpx;
				height: 104rpx;
				background: #ffffff;
				border-radius: 50%;
				box-shadow: 0rpx 0rpx 19rpx 0rpx rgba(0, 0, 0, 0.16);
				display: flex;
				justify-content: center;
				align-items: center;
				.img {
					width: 48rpx;
					height: 48rpx;
				}
			}
			.device-bg {
				position: absolute;
				left: 50%;
				top: 50%;
                z-index: 1;
				transform: translate(-50%, -50%);
				width: 231rpx;
				height: 231rpx;
                border-radius: 50%;
			}
		}
	}
}
.radar_container {
	position: relative;
	width: 231rpx;
	height: 231rpx;
	border-radius: 50%;
	overflow: hidden;
	cursor: pointer;
	display: flex;
	align-items: center;
	justify-content: center;
    z-index: 2;
}

.radar_wave {
	position: absolute;
	width: 20px;
	height: 20px;
	// transform: scale(0); // 初始状态改为从中间开始
	// background: rgba(31, 36, 52, 0.3);
	// border-radius: 50%;
	// animation: radar_wave-animation 3s infinite;

    border: 1px solid rgba(31, 36, 52, 0.08);
    border-radius: 50%;
    transform: scale(0); // 初始状态改为从中间开始
    box-shadow: inset 0 0 5px 1px rgba(31, 36, 52, 0.15); // 添加阴影
    animation: radar_wave-animation 3s infinite;
    z-index: 1;
}
.radar_wave:nth-child(1) {
	animation-delay: 0s;
}
.radar_wave:nth-child(2) {
	animation-delay: 1s;
}
.radar_wave:nth-child(3) {
	animation-delay: 2s;
}

@keyframes radar_wave-animation {
	0% {
		transform: scale(0); // 从中间开始
		opacity: 1;
	}
	100% {
		transform: scale(10); // 扩散到原来的10倍大小
		opacity: 0;
	}
}

	.picker-view {
		width: 100%;
		height: 300rpx;
		text-align: center;
	}

	/deep/ .picker-indicator {
		height: 100rpx;
		background-color: rgba(255, 255, 255, 0);
		z-index: 0;
		color: #000000;
		font-weight: 500;
	}

	.picker-view .picker-column:first-child .picker-indicator {
		border-radius: 16rpx 0 0 16rpx;
	}

	.picker-view .picker-column:last-child .picker-indicator {
		border-radius: 0 16rpx 16rpx 0;
	}

	.picker-mask {
		background-image: linear-gradient(#ffffff, rgba(255, 255, 255, 0.13)), linear-gradient(rgba(255, 255, 255, 0.123), #ffffff);
	}

	.picker-item {
		width: 100%;
		height: 100rpx !important;
		line-height: 100rpx;
		text-align: center;
		font-size: 32rpx;
	}

	.picker-item.pick-text {
		font-weight: 400;
		color: #000000;
		font-size: 32rpx;
		letter-spacing: 0.67rpx;
		font-weight: 500;
		overflow: hidden;
	}

	.pop {
		padding: 40rpx 50rpx 60rpx;
		height: 608rpx;

		.handleBle {
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 100rpx;


			.cancel,
			.confirm {
				width: 240rpx;
				height: 76rpx;
				background-color: #545dde;
				color: #ffffff;
				font-size: 30rpx;
				border-radius: 38rpx;
				text-align: center;
				line-height: 76rpx;
				margin-left: 44rpx;
			}

			.cancel {
				color: #545dde;
				background-color: #ffffff;
				border: 4rpx solid #545dde;
				line-height: 68rpx;
			}
		}
	}
</style>